/*
 * @(#)ServiceLocatorForRMI.java 1.0 2007-10-10
 * Copyright 2007 VandaGroup, Inc. All rights reserved.
 */
package com.vanda.util;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.ejb.EJBHome;
import javax.ejb.EJBObject;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 
 * @author 鲍利兵
 * 
 * 得到远程EJB服务
 */
public class ServiceLocatorForRMI {

    private static ServiceLocatorForRMI _instance;
    private static Map cache;

    static public ServiceLocatorForRMI getInstance(Properties prop) throws NamingException {
        if(_instance==null){
            _instance = new ServiceLocatorForRMI(prop);
            cache = Collections.synchronizedMap(new HashMap());
        }
        return _instance;
    }


    private InitialContext initialContext;

    private ServiceLocatorForRMI(Properties prop) throws NamingException {
        initialContext = new InitialContext(prop);
        
    }

    public Object getEJBHome(String jndiHomeName) throws NamingException {
        if (cache.containsKey(jndiHomeName)) {
			return cache.get(jndiHomeName);
		} else {
			if (initialContext != null) {
			    Object nsObject = initialContext.lookup(jndiHomeName);
		        cache.put(jndiHomeName, nsObject);
		        return nsObject;
			} else {
				throw new NamingException("ServiceLocatorForRMI:no InitialContext");
			}
		}
        
    }


    /**
     * 取得ejb实例
     * 
     * @param jndiHomeName
     * @return
     */
    public EJBObject create(String jndiHomeName) throws Exception {

        EJBHome home = (EJBHome) getEJBHome(jndiHomeName);

        Method method = home.getClass().getMethod("create", null);

        EJBObject obj = (EJBObject) method.invoke(home, null);

        return obj;

    }

}